const express = require('express');
const axios = require('axios');
const path = require('path');



function aggregateMessageContent(jsonString) {
    // 去除两端空白后，将相邻的 JSON 对象中间（} {）加上逗号，构造出合法的 JSON 数组字符串
    const arrayString = '[' + jsonString.trim().replace(/}\s*{/g, '},{') + ']';
    let jsonArray;
    try {
        jsonArray = JSON.parse(arrayString);
    } catch (e) {
        console.error("解析 JSON 失败", e);
        return "";
    }
    // 提取每个对象的 message.content，并拼接成一个字符串
    return jsonArray.map(item => item.message?.content || "").join("");
}

const setRoutes = (app) => {
    app.post('/ask', async (req, res) => {
        console.log('req.body---->',req.body);

        
        try {
            axios.post("http://127.0.0.1:11434/api/chat", req.body, {
            }).then(data => {
               const result =  aggregateMessageContent(data.data)
               console.log('result::: ', result);
                res.send(result);
                
            })
        } catch (error) {
            console.error(error);
            res.status(500).send("调用 Ollama 服务失败。");
        }
    });
};


// 编写一个测试的接口
const test = (app) => {
    app.get('/test-video', (req, res) => {
        const videoPath = path.resolve(__dirname, '../../public/test.mp4');
        res.sendFile(videoPath);
    });
};

module.exports = { setRoutes,test };